﻿using Storage.Core.Caching;
using Storage.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Storage.Mapping.BucketCut;
using Storage.Mapping;
using Storage.Entities;

namespace Storage.Services.BucketCut
{
    public class BucketCutService: IBucketCutService
    {
        private const string MODEL_KEY = "Storage.services.bucketcut";
        private ICacheManager _cacheManager;
        private IRepository<Entities.BucketCut> _bucketCutRepository;


        public BucketCutService(ICacheManager cacheManager,
            IRepository<Entities.BucketCut> bucketCutRepository)
        {
            this._cacheManager = cacheManager;
            this._bucketCutRepository = bucketCutRepository;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        public void deleteBucketCut(Guid id)
        {
           var item = _bucketCutRepository.getById(id);
            if (item == null) return;
            _bucketCutRepository.delete(item);
            _cacheManager.remove(MODEL_KEY);
        }

        /// <summary>
        /// 获取所有并缓存
        /// </summary>
        /// <returns></returns>
        public List<BucketCutMapping> getAllCach()
        {
            return _cacheManager.get <List<BucketCutMapping>>(MODEL_KEY, () =>
            {
                return _bucketCutRepository.Table.ToList().Select(item => item.toModel()).ToList();
            });
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        public void insertBucketCut(Entities.BucketCut entity)
        {
            if (_bucketCutRepository.Table.Any(o => o.Value == entity.Value && o.BucketId==entity.BucketId))
                return;
            _bucketCutRepository.insert(entity);
            _cacheManager.remove(MODEL_KEY);
        }
    }
}
